package com.lin.controller.teacher;

import com.aliyun.vod.upload.common.MD5Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lin.aop.WebLog;
import com.lin.entity.AclRole;
import com.lin.entity.AclUser;
import com.lin.service.AclUserService;
import com.lin.utils.JWTUtil;
import com.lin.utils.LinResult;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Copyright(C),2023年-03月-05,霖霖
 * FileNames:FileController
 * Author:霖霖
 * Date:2023/3/5 17:59
 * Description:
 * History:
 * <author>       <time>      <version>
 * 霖霖            2023/3/5      版本号
 */
@RestController()
@CrossOrigin
@RequestMapping("teacher")
public class LoginController {
    @Autowired
    private AclUserService userService;
    @WebLog("教师登录")
    @PostMapping("/login")
    public LinResult login(@RequestBody AclUser aclUser){
        aclUser.setPassword(MD5Util.md5(aclUser.getPassword()));
        QueryWrapper<AclUser> aclUserQueryWrapper = new QueryWrapper<>();
        aclUserQueryWrapper.eq("username",aclUser.getUsername());
        aclUserQueryWrapper.eq("password",aclUser.getPassword());
        AclUser admin = userService.getOne(aclUserQueryWrapper);
        if (admin==null){
            return LinResult.error().message("用户名或密码错误");
        }
        String token = JWTUtil.getJwtToken(admin.getId(), admin.getNickName());

        return LinResult.success().data("token",token);
    }
    @GetMapping("/getUserInfo")
    public LinResult getUserInfo(HttpServletRequest request){
        String adminId = JWTUtil.getMemberIdByJwtToken(request);
        AclUser admin = userService.getById(adminId);
        List<AclRole> rolesEntity = userService.getRoles(adminId);
        List<String> roles = rolesEntity.stream().map(AclRole::getRoleValue).collect(Collectors.toList());
        return LinResult.success().data("userId",adminId).data("role",roles).data("username",admin.getUsername()).data("realName",admin.getUsername()).data("avatar",admin.getAvatar());
    }
    @GetMapping("/logout")
    public LinResult logout(){
        return LinResult.success().data("token","");
    }
}
